package com.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSONObject;
import com.gmall.realtime.common.base.BaseApp;
import com.gmall.realtime.common.bean.TradeOrderBean;
import com.gmall.realtime.common.constant.Constant;
import com.gmall.realtime.common.function.DorisMapFunction;
import com.gmall.realtime.common.util.DateFormatUtil;
import com.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsTradeOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeOrderWindow().start(
                10028,
                1,
                "dws_trade_order_window",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }

    /**
     * 处理交易订单窗口统计逻辑
     * @param env Flink 流处理执行环境
     * @param stream 输入数据流，包含原始订单明细数据
     */
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        stream
                // 将JSON字符串转换为JSONObject
                .map(JSONObject::parseObject)
                // 设置事件时间和水印策略
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                // 允许5秒的乱序时间
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5L))
                                // 从数据中提取时间戳（单位转换毫秒）
                                .withTimestampAssigner((obj, ts) -> obj.getLong("ts") * 1000)
                                // 设置空闲等待时间为120秒，防止分区数据不更新导致窗口不触发
                                .withIdleness(Duration.ofSeconds(120L))
                )
                // 按用户ID进行分组
                .keyBy(obj -> obj.getString("user_id"))
                // 使用KeyedProcessFunction处理每个用户的订单数据
                .process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {

                    // 用于存储用户最后一次下单日期的状态
                    private ValueState<String> lastOrderDateState;

                    @Override
                    public void open(Configuration parameters) {
                        // 初始化状态，存储用户最后一次下单日期
                        lastOrderDateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<String>("lastOrderDate", String.class));
                    }

                    /**
                     * 处理每个订单数据，计算独立用户和新用户
                     */
                    @Override
                    public void processElement(JSONObject value,
                                               Context ctx,
                                               Collector<TradeOrderBean> out) throws Exception {
                        long ts = value.getLong("ts") * 1000;

                        // 转换当前事件时间为日期字符串
                        String today = DateFormatUtil.tsToDate(ts);
                        // 从状态中获取用户最后下单日期
                        String lastOrderDate = lastOrderDateState.value();

                        long orderUu = 0L;  // 独立用户计数
                        long orderNew = 0L; // 新用户计数

                        // 判断是否为当日首次下单
                        if (!today.equals(lastOrderDate)) {
                            orderUu = 1L;
                            // 更新最后下单日期状态
                            lastOrderDateState.update(today);

                            // 判断是否为新用户（首次下单）
                            if (lastOrderDate == null) {
                                orderNew = 1L;
                            }
                        }
                        // 仅当是独立用户时输出结果
                        if (orderUu == 1) {
                            out.collect(new TradeOrderBean("", "", "", orderUu, orderNew, ts));
                        }
                    }
                })
                // 定义5秒的滚动事件时间窗口
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5L)))
                // 窗口聚合操作
                .reduce(
                        // Reduce函数：累加窗口内的指标值
                        new ReduceFunction<TradeOrderBean>() {
                            @Override
                            public TradeOrderBean reduce(TradeOrderBean value1,
                                                         TradeOrderBean value2) {
                                value1.setOrderUniqueUserCount(value1.getOrderUniqueUserCount() + value2.getOrderUniqueUserCount());
                                value1.setOrderNewUserCount(value1.getOrderNewUserCount() + value2.getOrderNewUserCount());
                                return value1;
                            }
                        },
                        // 窗口处理函数：补充窗口时间信息
                        new ProcessAllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<TradeOrderBean> elements,
                                                Collector<TradeOrderBean> out) throws Exception {
                                TradeOrderBean bean = elements.iterator().next();
                                // 设置窗口开始和结束时间
                                bean.setStt(DateFormatUtil.tsToDateTime(ctx.window().getStart()));
                                bean.setEdt(DateFormatUtil.tsToDateTime(ctx.window().getEnd()));
                                // 设置分区日期
                                bean.setCurDate(DateFormatUtil.tsToDateForPartition(ctx.window().getStart()));

                                out.collect(bean);
                            }
                        }
                )
                // 转换为Doris数据库需要的格式
                .map(new DorisMapFunction<>())
                // 写入Doris数据库
                .sinkTo(FlinkSinkUtil.getDorisSink(
                        Constant.DORIS_DATABASE + ".dws_trade_order_window",
                        "dws_trade_order_window"));
    }

}